#include <signal.h>
#include <time.h>
#include <stdio.h>


typedef void (*timerTimeout)(union sigval v);

int createTimer(timer_t *timerId, timerTimeout func)
{
    struct sigevent sev;
 
    sev.sigev_notify = SIGEV_THREAD; //创建一个线程执行timer超时回调函数
    sev.sigev_signo = SIGRTMIN;		 //超时信号
    sev.sigev_notify_function = func; //超时回调函数
    sev.sigev_notify_attributes = NULL;
 
    /* 创建定时器 */
    if (timer_create (CLOCK_REALTIME, &sev, timerId) == -1)
    {
        printf("timer_create, error\n");
        return -1;
    }
 
    return 0;
}

int startTimer(timer_t timerid, long delay, long period)
{
    struct itimerspec it;

    it.it_value.tv_sec = (time_t)(delay/1000);     // 最初开始时间间隔
    it.it_value.tv_nsec = (delay % 1000) * 1000000;
    it.it_interval.tv_sec = (time_t)(period/1000);  // 后续按照该时间间隔
    it.it_interval.tv_nsec = (period % 1000) * 1000000;

    if (timer_settime(timerid, 0, &it, NULL) == -1)
    {
        printf("fail to timer_settime\n");
        return -1;
    }

    return 0;
}

int stopTimer(timer_t timerid)
{
    struct itimerspec it = {0};

    return timer_settime(timerid, 0, &it, NULL);
}

int deleteTimer(timer_t timerid)
{
    return timer_delete(timerid);
}


/*********************************main************************************/
void timerHandler(union sigval v)
{
	system("date");
}

int main(void)
{
	timer_t sTimer = 0;
	system("date");
	
	createTimer(&sTimer, timerHandler);
	startTimer(sTimer, 1000, 2000);
	
	while(1)
	{
		sleep(3);
		printf("sleep 3s\n");
	}
}